package pocker;

import pocker.exceptions.InvalidPlayerException;
import pocker.exceptions.IsDrawException;

/**
 * Created with IntelliJ IDEA.
 * User: gia
 * Date: 23.08.2012
 * Time: 11:34
 */
public class Game {
    private Player first, second;

    public Game(Player first, Player second) throws InvalidPlayerException {
        if (areInvalidPlayers(first, second))
            throw new InvalidPlayerException("Invalid players: " + first + ":" + second);
        this.first = first;
        this.second = second;
    }

    public Game(Player first, Player second, InputProvider inputProvider) throws InvalidPlayerException {
        if (areInvalidPlayers(first, second))
            throw new InvalidPlayerException("Invalid players: " + first + ":" + second);
        inputProvider.provideBetSumToPlayer(first);
        inputProvider.provideBetSumToPlayer(second);
        this.first = first;
        this.second = second;
    }

    private boolean areInvalidPlayers(Player first, Player second) {
        return first == null || second == null || first.getName().equals(second.getName());
    }


    public Player getWinner() throws IsDrawException {
        if (isDraw())
            throw new IsDrawException("It's a draw between " + first.getName() + " and " + second.getName());

        int prize = first.getBet() + second.getBet();

        if (first.hasEqualCards() && second.hasEqualCards())
            return setWinnerPrize(biggerByFirstCard(), prize);

        if (first.hasEqualCards())
            return setWinnerPrize(first, prize);

        if (second.hasEqualCards())
            return setWinnerPrize(second, prize);

        if (first.getCard1() == second.getCard1())
            return setWinnerPrize(biggerBySecondCard(), prize);
        return setWinnerPrize(biggerByFirstCard(), prize);

    }

    private Player setWinnerPrize(Player first, int prize) {
        first.setBet(prize);
        return first;
    }

    private Player biggerByFirstCard() {
        if (first.getCard1() > second.getCard1())
            return first;
        return second;
    }

    private Player biggerBySecondCard() {
        if (first.getCard2() > second.getCard2())
            return first;
        return second;
    }


    public boolean isDraw() {
        return first.getCard1() == second.getCard1() && first.getCard2() == second.getCard2();
    }

    public void save(GameSerializer gameSerializer) throws IsDrawException {

        String result;
        Player winner;
        if (isDraw())
            result = "It's a draw.";
        else {
            winner = getWinner();
            result = "The winner is: " + winner.getName() + " with sum:" + winner.getBet();
        }

        gameSerializer.writeString(result);
    }

    public Player getFirst() {
        return first;
    }

    public Player getSecond() {
        return second;
    }
}
